package com.icongyou.enterprise.talent_pool.service.impl;

import com.icongyou.enterprise.talent_pool.entity.TalentSearchHistory;
import com.icongyou.enterprise.talent_pool.entity.vo.TalentSearchHistoryListVO;
import com.icongyou.enterprise.talent_pool.entity.vo.TalentSearchHistoryVO;
import com.icongyou.enterprise.talent_pool.mapper.TalentSearchHistoryMapper;
import com.icongyou.enterprise.talent_pool.service.TalentSearchHistoryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class TalentSearchHistoryServiceImpl implements TalentSearchHistoryService {

    private final TalentSearchHistoryMapper talentSearchHistoryMapper;

    private static final int MAX_HISTORY_COUNT = 20;

    @Override
    @Transactional
    public void saveSearchHistory(String userId, String demandText) {
        if (userId == null || demandText == null || demandText.trim().isEmpty()) {
            return;
        }

        String trimmedDemandText = demandText.trim();
        LocalDateTime now = LocalDateTime.now();

        // 检查是否已存在相同的搜索记录
        var existingHistory = talentSearchHistoryMapper.findByUserIdAndDemandText(userId, trimmedDemandText);

        if (existingHistory.isPresent()) {
            // 更新现有记录
            talentSearchHistoryMapper.updateSearchCount(userId, trimmedDemandText, now);
        } else {
            // 插入新记录前检查数量限制
            int currentCount = talentSearchHistoryMapper.countByUserId(userId);
            if (currentCount >= MAX_HISTORY_COUNT) {
                // 删除最旧的记录
                int deleteCount = currentCount - MAX_HISTORY_COUNT + 1;
                talentSearchHistoryMapper.deleteOldestByUserId(userId, deleteCount);
            }

            // 插入新记录
            TalentSearchHistory history = new TalentSearchHistory();
            history.setId(UUID.randomUUID().toString());
            history.setUserId(userId);
            history.setDemandText(trimmedDemandText);
            history.setSearchTime(now);
            history.setSearchCount(1);
            history.setLastSearchTime(now);

            talentSearchHistoryMapper.insert(history);
        }
    }

    @Override
    public List<TalentSearchHistoryVO> getSearchHistory(String userId) {
        List<TalentSearchHistory> histories = talentSearchHistoryMapper
                .findByUserIdOrderByLastSearchTimeDesc(userId, MAX_HISTORY_COUNT);

        return histories.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public TalentSearchHistoryListVO getSearchHistoryPage(String userId, Integer page, Integer size) {
        // 由于需求是固定20条，这里简单实现分页
        List<TalentSearchHistoryVO> allHistories = getSearchHistory(userId);

        int pageNum = page != null ? page : 1;
        int pageSize = size != null ? size : 10;
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, allHistories.size());

        TalentSearchHistoryListVO result = new TalentSearchHistoryListVO();
        result.setHistoryList(allHistories.subList(startIndex, endIndex));
        result.setCurrentPage(pageNum);
        result.setPageSize(pageSize);
        result.setTotalCount(allHistories.size());
        result.setHasMore(endIndex < allHistories.size());

        return result;
    }

    @Override
    @Transactional
    public boolean deleteSearchHistory(String userId, String historyId) {
        try {
            int deleted = talentSearchHistoryMapper.deleteById(historyId);
            return deleted > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean clearSearchHistory(String userId) {
        try {
            // 获取用户的所有历史记录ID
            List<TalentSearchHistory> histories = talentSearchHistoryMapper
                    .findByUserIdOrderByLastSearchTimeDesc(userId, Integer.MAX_VALUE);

            for (TalentSearchHistory history : histories) {
                talentSearchHistoryMapper.deleteById(history.getId());
            }

            return true;
        } catch (Exception e) {
            return false;
        }
    }

    private TalentSearchHistoryVO convertToVO(TalentSearchHistory entity) {
        TalentSearchHistoryVO vo = new TalentSearchHistoryVO();
        vo.setId(entity.getId());
        vo.setDemandText(entity.getDemandText());
        vo.setSearchCount(entity.getSearchCount());
        vo.setLastSearchTime(entity.getLastSearchTime());
        vo.setCreatedTime(entity.getCreatedTime());
        return vo;
    }
}